package control;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;

import model.dao.MajorDao;
import model.dao.Student_MajorDao;
import model.entity.Major;

/**
 * Servlet implementation class GetMajor
 */
@WebServlet("/GetMajor")
public class GetMajor extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetMajor() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    HttpSession session=request.getSession();
	    String stuName=(String) session.getAttribute("userName");
	    System.out.println("stuName: " + stuName);
	    String majorid=new String("major_id");
	    String stuid=new String("student_id");
	    String id=new String("id");
	    String name=new String("name");
	    Integer stuNameVal=new Integer(Integer.valueOf(stuName));
	    Student_MajorDao smd=new Student_MajorDao();
		MajorDao majorDao=new MajorDao();
		List<Object> maIdList=smd.getSigleSelect(majorid, stuid, stuNameVal);
		String str="[";
		for (Object maId : maIdList) {
			List<Object> majorList=majorDao.getSigleSelect(name, id, maId);
			
			for (Object major : majorList) {
				str+="{\"name\":\"" + major + "\"},";
			}
		}
		str=str.substring(0, str.length()-1);
		str+="]";
		response.setCharacterEncoding("utf-8");
		PrintWriter out=response.getWriter();
		out.print(str);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
